package cn.flying.cloud.oauth.server.log;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.system.feign.UserInfoApiClient;
import cn.flying.cloud.system.model.LoginLog;

/**
 * @author: admin
 * @date: 2025年02月27日 10:12
 * @version: 1.0
 */
@Component
public class LoginLogHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserInfoApiClient userInfoApiClient;

    public void loginFailed(String username, String tenantId, String ip, String remark) {
        LoginLog log = new LoginLog();
//        log.setUserId("");
        log.setUserName(username);
//        log.setName(userDetail.getName());
        log.setHappenType("用户登录");
        log.setHappenTime(LocalDateTime.now());
        log.setHappenIp(ip);
        log.setRemark(remark);
        log.setTenantId(tenantId);
        log.setCreatedBy(username);
        log.setCreatedTime(LocalDateTime.now());
        log.setUpdatedBy(username);
        log.setUpdatedTime(LocalDateTime.now());

        loginLog(log);
    }

    public void loginSuccess(String username, String tenantId, String ip) {
        LoginLog log = new LoginLog();
//        log.setUserId("");
        log.setUserName(username);
//        log.setName(userDetail.getName());
        log.setHappenType("用户登录");
        log.setHappenTime(LocalDateTime.now());
        log.setHappenIp(ip);
        log.setRemark("用户登录成功");
        log.setTenantId(tenantId);
        log.setCreatedBy(username);
        log.setCreatedTime(LocalDateTime.now());
        log.setUpdatedBy(username);
        log.setUpdatedTime(LocalDateTime.now());

        loginLog(log);
    }

    public void logout(String username, String tenantId, String ip) {
        LoginLog log = new LoginLog();
//        log.setUserId("");
        log.setUserName(username);
//        log.setName(userDetail.getName());
        log.setHappenType("用户注销");
        log.setHappenTime(LocalDateTime.now());
        log.setHappenIp(ip);
        log.setRemark("用户注销登录");
        log.setTenantId(tenantId);
        log.setCreatedBy(username);
        log.setCreatedTime(LocalDateTime.now());
        log.setUpdatedBy(username);
        log.setUpdatedTime(LocalDateTime.now());

        loginLog(log);
    }

    public void loginLog(LoginLog log) {
        log.setCreatedTime(LocalDateTime.now());
        log.setUpdatedTime(LocalDateTime.now());

        CompletableFuture.runAsync(() -> {
            try {
                userInfoApiClient.loginLog(log);
            } catch (Exception e) {
                logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
            }
        });

    }
}
